import base64
import hashlib
import time
import requests
import json

# OCR手写文字识别接口地址
URL = "example_base_url"
# 应用APPID(必须为webapi类型应用,并开通手写文字识别服务)
APPID = "exampleId"
# 接口密钥(webapi类型应用开通手写文字识别后，控制台--我的应用---手写文字识别---相应服务的apikey)
API_KEY = "example_api_key"


# 鉴权获取头部信息
def get_header(_language, _location):
    cur_time = str(int(time.time()))
    param = json.dumps({"language": _language, "location": _location})
    param_base64 = base64.b64encode(param.encode('utf-8')).decode('utf-8')

    m2 = hashlib.md5()
    str1 = API_KEY + cur_time + param_base64
    m2.update(str1.encode('utf-8'))
    checkSum = m2.hexdigest()

    header = {
        'X-CurTime': cur_time,
        'X-Param': param_base64,
        'X-Appid': APPID,
        'X-CheckSum': checkSum,
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
    }
    print("header:", header)

    return header


def get_body(filepath):
    with open(filepath, 'rb') as f:
        bigfile = f.read()
    data = {'image': base64.b64encode(bigfile).decode('utf-8')}
    return data


# 识别图片文字接口
def identify(filepath):
    # 语种设置
    language = "cn|en"
    # 是否返回文本位置信息
    location = "false"

    headers = get_header(language, location)

    # 使用正确的关键字参数传递data
    resp = requests.post(URL, headers=headers, data=get_body(filepath))
    # resp 示例：{"code":"0","data":{"block":[{"type":"text","line":[{"confidence":1,"word":[{"content":"H20"}]}]}]},
    # "desc":"success","sid":"wcr01dfa831@dx2fb51b02a5406f1a00"}

    result = resp.json()
    data = result.get('data', {})
    print("xfyun请求结果：", data)

    text = ""
    if not data or "block" not in data:
        return text

    for block in data['block']:
        for line in block.get("line", []):
            for word in line.get("word", []):
                text = word.get("content", "")

    return text
